package com.shiguiwu.springboot3.websocket;

import com.shiguiwu.springboot3.dto.AuthUser;
import com.shiguiwu.springboot3.service.TokenService;
import com.shiguiwu.springboot3.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
@Slf4j
@Component
public class AuthHandshakeInterceptor implements HandshakeInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Map<String, Object> attributes) {
        // 从请求中获取Token或用户ID [1,2](@ref)
        String authHeader = ((ServletServerHttpRequest) request).getServletRequest().getHeader("Authorization");
        // ... 验证Token逻辑
        // 从请求头获取Token
        //final String authHeader = request.getHeader("token");
        String token = null;
        String jwt = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            jwt = authHeader.substring(7);
            token = jwtUtils.extractToken(jwt);
        }

        if (jwtUtils.isTokenExpired(jwt)) {
            log.error("Token is expired {}", authHeader);
            return false;
        }

        // 验证Token有效性
        if (token != null) {
            AuthUser user = tokenService.getToken(token);
            Long userId = user.getId();
            // 将用户ID放入属性，后续在Handler中可通过session.getAttributes()获取
            attributes.put("userId", userId.toString());
            return true; // 返回true允许连接
        }
        return false;
    }


    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }

}